package org.example.Filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.example.Utils.JwtUtil;

import java.io.IOException;

//@WebFilter("/*")
@Slf4j
public class TokenFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        log.info("程序开始执行");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        //强制转换
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        String token = request.getHeader("token");
        String url = request.getRequestURI();

        //判断是否未登录操作,如果是则放行
        if(url.contains("/login")){
            //放行
            log.info("登录操作");
            filterChain.doFilter(request, response);
            return;//由于代码执行后会返回到此处
        }
        //判断令牌是否为空
        if(token == null || token.isEmpty()){
            log.info("令牌为空或者不存在");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//返回401状态码
            return;
        }

        //校验令牌的正确性
        try {
            JwtUtil.parseToken(token);
        } catch (Exception e) {
            log.info("令牌非法");
            response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);//返回401状态码
            return;
        }
        //解析令牌正确直接放行
        filterChain.doFilter(request, response);

    }

    @Override
    public void destroy() {
        log.info("程序结束执行，服务器停止");
    }
}
